package com.itisyue.fun.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
    Logger log = LoggerFactory.getLogger(ThreadPoolTaskConfig.class);

    private static int cpu = Runtime.getRuntime().availableProcessors();
    private static final int corePoolSize = cpu * 4;
    private static final int maxPoolSize = cpu * 40;
    private static final int keepAliveTime = 10;
    private static final int queueCapacity = 100;
    private static final String threadNameprefix = "Async-Service-";

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        log.info("初始化线程池配置... 服务器cpu数="+cpu+", corePoolSize="+corePoolSize+", maxPoolSize="+maxPoolSize+", queueCapacity="+queueCapacity);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNameprefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();
        return executor;

    }
}
